package com.zmy.springboot.controller;

import com.github.pagehelper.PageInfo;
import com.zmy.springboot.bean.AccountSearch;
import com.zmy.springboot.bean.AccountType;
import com.zmy.springboot.bean.PublicAccount;
import com.zmy.springboot.service.AccountTypeService;
import com.zmy.springboot.service.PublicAccountService;
import com.zmy.springboot.util.PageConstances;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @PROJECT_NAME：springboot+thymeleaf-1-7
 * @author： zhangyaoyao
 * @date： 2020/1/7 22:30
 * @ 听说你要在海边买一所房子和 你可爱的松子一起住在哪里
 */
@Controller
public class PublicAccountController {
    @Autowired
    private PublicAccountService publicAccountService;
    @Autowired
    private AccountTypeService accountTypeService;


    @RequestMapping("/getPublicAccountList.html")
        public String  getPublicAccountList(@RequestParam(defaultValue = "1")Integer index, AccountSearch accountSearch, Model model){
//        System.out.println(accountSearch);
        if (index == null || index < 1){
            index = 1;
        }
        PageInfo<PublicAccount> publicAccountPage = publicAccountService.getPublicAccountList(index, PageConstances.PAGE_SIZE, accountSearch);
        model.addAttribute("publicAccountPage",publicAccountPage);
        List<AccountType> accountTypes = accountTypeService.getAccountTypes();
        model.addAttribute("accountTypes",accountTypes);
        return  "publicAccountList";
    }

    @RequestMapping("/getPublicAccountById.html")
    public String getPublicAccountById(Integer id,Model model){
        PublicAccount publicAccount = publicAccountService.getPublicAccountById(id);
        model.addAttribute("publicAccount",publicAccount);
        List<AccountType> accountTypes = accountTypeService.getAccountTypes();
        model.addAttribute("accountTypes",accountTypes);
        return "updatePublicAccount";
    }

    @RequestMapping("/updatePublicAccount.html")
    public void updatePublicAccount(PublicAccount publicAccount, HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
        try {
            PrintWriter out = response.getWriter();
            int len = publicAccountService.updatePublicAccount(publicAccount);
            if (len > 0) {
                out.print("<script>alert('修改成功！');location.href='/getPublicAccountList.html';</script>");
                return;
            }
            else {
                out.print("<script>alert('修改失败！');location.href='/getPublicAccountById?id="+publicAccount.getId()+"';</script>");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
